"""
测试subprocess模块的阻塞功能
"""
import threading
import time

import requests
import re
import json
import subprocess as sp
from threading import Thread

from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile

from btools import FileTools, Logger

fts = FileTools()
logger = Logger()
wordpath = fts.getworkdir()

url = 'https://www.bilibili.com/video/BV1Ci4y1P7Zw?spm_id_from=333.851.b_7265706f7274466972737432.9'
headers = {
    'user-agent': r'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
    'referer': r'https://www.bilibili.com/'
}


# 获取网页源代码
def request_file():
    """
    下载文件
    """

    def request_file_video():
        """
        下载视频
        """
        r_video = requests.get(video_url, headers=headers)
        with open('video.mp4', 'wb') as f:
            f.write(r_video.content)

    def request_file_audio():
        """
        下载音频
        """
        r_audio = requests.get(audio_url, headers=headers)
        with open('audio.mp3', 'wb') as f:
            f.write(r_audio.content)

    r = requests.get(url, headers=headers)
    pattern = r'window.__playinfo__=(.*)</script><script>window.__INITIAL_STATE__='
    pattern2 = r'<title data-vue-meta="true">(.*)</title>'
    source_data = re.findall(pattern, r.text.strip())
    video_url = json.loads(source_data[0]).get('data').get('dash').get('video')[0].get('baseUrl')
    audio_url = json.loads(source_data[0]).get('data').get('dash').get('audio')[0].get('baseUrl')
    logger.info(f'video_url1:{video_url}')
    logger.info(f'audio_url1:{audio_url}')
    video_title = re.findall(pattern2, r.text.strip())[0]
    fts.mkdir(video_title)
    fts.chdir(video_title)
    vt = Thread(target=request_file_video)
    at = Thread(target=request_file_audio)
    vt.setDaemon(True)
    at.setDaemon(True)
    vt.start()
    vt.join()
    at.start()
    at.join()
    print('下载完成!')
    merge()


def merge():
    """
    合并音频视频
    """
    print('开始合并...')
    cmd1 = r'ffmpeg -y -i video.mp4 -i audio.mp3 -c:v copy -c:a aac -strict experimental new_video.mp4'
    cmd2 = r'rm video.mp4 audio.mp3'
    # 执行合并动作
    sp.Popen(cmd1, shell=True).communicate()
    sp.Popen(cmd2, shell=True).communicate()
    fts.chdir(wordpath)
    logger.info('视频下载成功!')


def download_handle():
    """
    点击下载按钮时触发
    """
    tss = []
    t_request_file = Thread(target=request_file)
    t_request_file.start()


app = QApplication([])
ui_path = fts.getpath('test.ui')
file = QFile(ui_path)  # 文件所在路径
file.open(QFile.ReadOnly)
ui = QUiLoader().load(file)
con = ui.textbrowser_console
ui.button_download.clicked.connect(download_handle)
ui.button_merge.clicked.connect(merge)
ui.show()
app.exec_()
